package com.test.demo.annotation.proxy.http.registrar;

import com.test.demo.annotation.proxy.http.annotation.EnableMyAutoConfiguration;
import com.test.demo.annotation.proxy.http.annotation.HttpClient;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;

/**
 * @ClassName MyAutofigurationRegistrar
 * @Description
 * @Author laigl
 * @Date 2020/2/22 22:41
 **/
public class MyAutofigurationRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    private ResourceLoader resourceLoader;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        //获取注解属性的键值对
        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableMyAutoConfiguration.class.getName()));
        String basePackage = annoAttrs.getString("basePackage");

        //使用implClass来切换代理实现方式
        //@EnableMyFeginClientAutoConfiguration(basePackage = "com.luna.springbootpractice.demo.service",implClass = MyFeginClientCgLibFactoryBean.class)
        Class<? extends AbstractFactoryBean> implClass = annoAttrs.getClass("implClass");

        // 扫描带有MyFeginClientScanner注解的接口
        MyClassPathBeanDefinitionScanner scanner = new MyClassPathBeanDefinitionScanner(registry);
        scanner.setResourceLoader(resourceLoader);
        scanner.addIncludeFilter(new AnnotationTypeFilter(HttpClient.class));

        scanner.setFactoryBeanImplClass(implClass);
        scanner.doScan(basePackage);
    }

}
